package com.example.shiroplusdemo.controller;


import com.example.shiroplusdemo.entity.CustomPage;
import com.example.shiroplusdemo.entity.FrontPage;
import com.example.shiroplusdemo.entity.Role;
import com.example.shiroplusdemo.repository.RoleRepository;
import com.example.shiroplusdemo.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-12
 **/
@Controller
@RequestMapping("/role")
@Slf4j
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleRepository roleRepository;

    /**
     * 跳转到role管理页面
     * @param edit
     * @param model
     * @return
     */
    @RequestMapping("/rolePage")
    public String role(String edit,Model model){
        //edit判断是否编辑成功
        model.addAttribute("edit",edit);
        return "role/role";
    }

    /**
     * 获取角色分页对象
     * @param page
     * @return
     */
    @RequestMapping("/getRoleListWithPager")
    @ResponseBody
    public CustomPage<Role> getRoleListWithPager(FrontPage page){
        Page<Role>  rolePage = roleService.getRoleList(page);
        CustomPage<Role> customPage = new CustomPage<Role>(rolePage,page);
        return customPage;
    }

    @RequestMapping("/editPage/{Id}")
    public String editPage(@PathVariable("Id")String Id,Model model){
        Role role = roleRepository.findById(Integer.parseInt(Id));
        model.addAttribute("role",role);
        return "role/edit";
    }

//    @RequestMapping("/delete")
//    @ResponseBody //TODO

    @RequestMapping("/edit")
    public String edit(Role roleUpdate,Model model){
        Role role = roleRepository.findById(roleUpdate.getId());
        if(role==null){
            roleRepository.save(roleUpdate);
            return "redirect:rolePage?edit=true";
        } else if(role!=null){
            BeanUtils.copyProperties(roleUpdate,role);
            roleRepository.save(role);
            return "redirect:rolePage?edit=true";
        } else{
            return "redirect:rolePage?edit=false";
        }
    }



}
